/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultarModalidades.java
 *
 * Created on 02/05/2011, 00:17:59
 */
package Interface;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import ludi.Modalidade;
import ludi.Usuario;
import utils.BancoDeDados;

/**
 *
 * @author alison
 */
public class ConsultarModalidades extends javax.swing.JInternalFrame {

    BancoDeDados banco;
    Usuario user;
    /** Creates new form ConsultarModalidades */
    public ConsultarModalidades(BancoDeDados banco, Usuario user) {
        this.banco = banco;
        this.user = user;
        initComponents();
        if (user.getPermissoes() == 2){
            botaoGerenciar.setEnabled(false);
        }
        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabelaModalidades = new javax.swing.JScrollPane();
        tabelaModalidades = new javax.swing.JTable();
        botaoGerenciar = new javax.swing.JButton();
        botaoCancelar = new javax.swing.JButton();
        campoBusca = new javax.swing.JTextField();
        botaoBuscar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Consultar Modalidades");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tabelaModalidades.setAutoCreateRowSorter(true);
        tabelaModalidades.setBackground(new java.awt.Color(254, 254, 254));
        ArrayList<Integer> listaDeModalidades;
        try {
            listaDeModalidades = banco.getListaDeModalidades(null, null);
        } catch (SQLException e) {
            e.printStackTrace();
            listaDeModalidades = null;
        }
        tabelaModalidades.setModel(modeloTabelaModalidades(listaDeModalidades));
        tabelaModalidades.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scrollTabelaModalidades.setViewportView(tabelaModalidades);
        tabelaModalidades.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        botaoGerenciar.setText("Gerenciar Modalidade Selecionada");
        botaoGerenciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoGerenciarActionPerformed(evt);
            }
        });

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarActionPerformed(evt);
            }
        });

        campoBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoBuscaActionPerformed(evt);
            }
        });

        botaoBuscar.setText("Pesquisar");
        botaoBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(scrollTabelaModalidades, javax.swing.GroupLayout.DEFAULT_SIZE, 823, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botaoCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoGerenciar)
                        .addGap(24, 24, 24))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botaoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(458, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoBuscar))
                .addGap(18, 18, 18)
                .addComponent(scrollTabelaModalidades, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoGerenciar)
                    .addComponent(botaoCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarActionPerformed

    private void botaoGerenciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoGerenciarActionPerformed
        if (tabelaModalidades.getSelectedRow() < 0){
            JOptionPane.showMessageDialog(this, "Selecione uma modalidade!", "Consultar Modalidade", JOptionPane.INFORMATION_MESSAGE);
        } else {
            String coluna;
            int i = -1;
            do {
                i++;
                coluna = tabelaModalidades.getColumnName(i);
            } while (!(coluna.equals("ID")));

           CriarModalidade frame;
            try {
                frame = new CriarModalidade(banco, banco.getModalidade(Integer.parseInt(tabelaModalidades.getValueAt(tabelaModalidades.getSelectedRow(), i).toString())));
                frame.setVisible(true);
                this.getDesktopPane().add(frame);
                try {
                    frame.setSelected(true);
                } catch (java.beans.PropertyVetoException e) {}
            } catch (SQLException ex) {
                Logger.getLogger(ConsultarUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_botaoGerenciarActionPerformed

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
        ArrayList<Integer> listaDeModalidades;
        try {
            listaDeModalidades = banco.getListaDeModalidades(null, null);
        } catch (SQLException e) {
            e.printStackTrace();
            listaDeModalidades = null;
        }
        tabelaModalidades.setModel(modeloTabelaModalidades(listaDeModalidades));
    }//GEN-LAST:event_formInternalFrameActivated

    private void botaoBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscarActionPerformed
        busca();
    }//GEN-LAST:event_botaoBuscarActionPerformed

    private void campoBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoBuscaActionPerformed
        busca();
    }//GEN-LAST:event_campoBuscaActionPerformed

    private void busca(){
        try {
            tabelaModalidades.setModel(modeloTabelaModalidades(banco.getListaDeModalidades(campoBusca.getText(), "nome")));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private DefaultTableModel modeloTabelaModalidades(ArrayList<Integer> listaDeModalidades){
        String[][] dados = new String [0][];
        String[] colunas = new String [] {"ID", "Nome", "Gênero", "Máx. de Times", "Mín. de Atletas", "Máx. de Atletas"};

        DefaultTableModel modelo = new DefaultTableModel(dados, colunas){
             Class[] types = new Class [] {
                 java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
             };
             boolean[] canEdit = new boolean [] {
                 false, false, false, false, false, false
             };

             @Override
             public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
             }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };

        for (int i = 0; i < listaDeModalidades.size(); i++){
              try {
                   Modalidade modalidade = banco.getModalidade(listaDeModalidades.get(i));
                   String genero = (modalidade.getGenero() == 1)? "Masculino" : "Feminino";
                   modelo.addRow(new Object [] {modalidade.getId(), modalidade.getNome(), genero, modalidade.getQuantMaxTimes(), modalidade.getQuantMinAtletas(), modalidade.getQuantMaxAtletas()});
               }catch (SQLException ex) {
                   Logger.getLogger(CriarTime.class.getName()).log(Level.SEVERE, null, ex);
               }
         }
        return modelo;
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoBuscar;
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoGerenciar;
    private javax.swing.JTextField campoBusca;
    private javax.swing.JScrollPane scrollTabelaModalidades;
    private javax.swing.JTable tabelaModalidades;
    // End of variables declaration//GEN-END:variables
}
